/*
 * This file is Copyright 2002-2006 Loyola University Chicago,
 * Department of Computer Science and the Emerging Technologies Laboratory.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License via
 *    http://www.apache.org/licenses/LICENSE-2.0.
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.citep.web.admin.uploads.server;

import java.io.*;
import javax.servlet.http.*;
import javax.servlet.*;
import java.util.List;
import java.util.Iterator;
import java.util.ArrayList;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.*;
import org.apache.commons.fileupload.servlet.*;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.citep.business.User;
import com.citep.business.sessions.AccountSession;
import com.citep.business.sessions.TransactionSession;
import com.citep.business.sessions.UserSession;
import com.citep.formats.input.transactions.*;
import com.citep.formats.input.accounts.*;
import com.citep.formats.input.*;
import com.citep.web.admin.accounts.server.SessionLabels;

public class UploadServlet extends HttpServlet {
	ApplicationContext appContext;
	AccountSession accountSession;
	TransactionSession transactionSession;
	UserSession userSession;
	AccountImportContext accountImportCtx;
	TransactionImportContext transactionImportCtx;

	public void init(ServletConfig config) {
		appContext = new ClassPathXmlApplicationContext("applicationContext.xml");
		//get our session beans from the application context
		accountSession = (AccountSession)appContext.getBean("accountSession");
		transactionSession = (TransactionSession)appContext.getBean("transactionSession");
		userSession = (UserSession)appContext.getBean("userSession");
		accountImportCtx = (AccountImportContext)appContext.getBean("accountImport");
		transactionImportCtx = (TransactionImportContext)appContext.getBean("transactionImport");
	}
	
	private void addStatementToSession(HttpServletRequest request, ImportedStatement s) {
		ArrayList<ImportedStatement> statements = (ArrayList<ImportedStatement>)request.getSession().getAttribute(SessionLabels.IMPORTED_STATEMENTS);
		//if there is no list of statements in the session, create one now
		if(statements == null) {
			statements = new ArrayList<ImportedStatement>();
			request.getSession().setAttribute(SessionLabels.IMPORTED_STATEMENTS, statements);
		}
		
		statements.add(s);
	}
	
	protected void doPost(HttpServletRequest request, HttpServletResponse response)  throws IOException  {
		
		FileItemFactory factory = new DiskFileItemFactory();
		ServletFileUpload upload = new ServletFileUpload(factory);
		
		User u = (User)request.getSession().getAttribute(SessionLabels.AUTHENTICATED_USER);
		
		System.out.println("Authenticated user: " + u);

		response.setContentType("text/plain");
		try {
			List items = upload.parseRequest(request);
			Iterator it = items.iterator();
			
			int numStatements = 0; //number of imported statements
			int numEntries = 0; //number of imported entries
			
			while(it.hasNext()) {
				FileItem item = (FileItem)it.next();
				if(!item.isFormField() && "importFile".equals(item.getFieldName())) {
					InputStream in = item.getInputStream();
					System.out.println("t" + transactionImportCtx);
					for(ImportedStatement statement:transactionImportCtx.readSource(new DataInputStream(new BufferedInputStream(in)), ImportFileTypes.OFX1_STATEMENT)) {
						System.out.println("****************** Statement " + numStatements);
						for(ImportedEntry e:statement.getEntries())
							System.out.println(e);
						addStatementToSession(request,statement);
						
						numStatements++;
						numEntries += statement.getEntries().size();
					}
				}
			}
			
			response.getWriter().write("__OK__" + numStatements + "__" + numEntries + "__");
			
		} catch (FileUploadException e) {
			response.getWriter().write("__ERR__" + "File upload error: " + e.getMessage() + "__");
			e.printStackTrace();
		} catch (ImportException e) {
			response.getWriter().write("__ERR__" + "Import error: " + e.getMessage() + "__");
			e.printStackTrace();
		}
		
	}
}
